package net.nagaseyasuhito.kinsenka.wicket;

import javax.persistence.NoResultException;

import net.nagaseyasuhito.kinsenka.persist.dao.UserDao;
import net.nagaseyasuhito.kinsenka.persist.entity.User;

import org.apache.wicket.authroles.authentication.AuthenticatedWebSession;
import org.apache.wicket.authroles.authorization.strategies.role.Roles;
import org.apache.wicket.injection.Injector;
import org.apache.wicket.request.Request;

import com.google.inject.Inject;

public class KinsenkaSession extends AuthenticatedWebSession {
	private static final long serialVersionUID = 1L;

	public static KinsenkaSession get() {
		return (KinsenkaSession) AuthenticatedWebSession.get();
	}

	private Long id;

	@Inject
	private UserDao userDao;

	public KinsenkaSession(Request request) {
		super(request);
		Injector.get().inject(this);
	}

	@Override
	public boolean authenticate(String signInId, String password) {
		try {
			this.id = this.userDao.findBySignInIdAndPassword(signInId, password).getId();

			return true;
		} catch (NoResultException e) {
			return false;
		}
	}

	@Override
	public Roles getRoles() {
		return this.id == null ? null : new Roles(Roles.USER);
	}

	public User getUser() {
		if (this.id == null) {
			return null;
		}

		User criteria = new User();
		criteria.setId(this.id);

		return this.userDao.findByCriteria(criteria);
	}

	@Override
	public void signOut() {
		super.signOut();
		this.id = null;
	}
}
